#include "memory.h"

struct Memory* init_memory() {
  struct Memory *root = (struct Memory*)malloc(sizeof(struct Memory));
  root->id = 0;
  root->data = NULL;
  root->next = NULL;
  return root;
}

struct MemResult new_memory(struct Memory *mem, size_t size) {
  struct Memory *m = mem;
  while (m->next != NULL) {
    m = m->next;
  }

  struct Memory *node = (struct Memory*)malloc(sizeof(struct Memory));
  m->next = node;
  node->id = m->id + 1;
  node->data = malloc(size);
  node->next = NULL;

  struct MemResult res;
  res.id = node->id;
  res.data = node->data;
  return res;
}

bool free_memory(struct Memory *mem, int id) {
  if (id < 1) {
    return false;
  }
  
  struct Memory *m = mem;
  struct Memory *prev = NULL;
  while (m->next != NULL) {
    prev = m;
    m = m->next;
    if (m->id == id) {
      struct Memory *current = m;
      if (current->data != NULL) {
	free(current->data);
	current->data = NULL;
      }
      free(current);
      current = NULL;
      prev->next = m->next;
      return true;
    }
  }
  return false;
}

void free_memory_all(struct Memory *mem) {
  struct Memory *m = mem;
  struct Memory *current = NULL;
  while (m != NULL) {
    current = m;
    if (current->data != NULL) {
      free(current->data);
      current->data = NULL;
    }
    m = m->next;
    current->next = NULL;
    free(current);
    current = NULL;
  }
}

int memory_count(struct Memory *mem) {
  struct Memory *m = mem;
  int count = 0;
  while (m->next != NULL) {
    ++count;
    m = m->next;
  }
  return count;
}
